package com.xiaoma.component;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description:
 * @Author: xiaoma
 * @Date: 2021/8/27 15:22
 */
@Component
public class AliOssCompent {

    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    String accessId;

    @Value("${spring.cloud.alicloud.secret-key}")
    String accessKey;

    /**
     * @Description  流式上传
     * @Author Xiaoma
     * @Date 2021/8/27 16:54
     * @param localPath
     * @param fileName
     * @return java.lang.Boolean
     **/
    public Boolean upload2OssByStream(String localPath, String fileName) {
        try {
            ossClient.putObject(bucket, fileName, new FileInputStream(localPath));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
    }
    /**
     * @Description  File文件上传
     * @Author Xiaoma
     * @Date 2021/8/27 16:53
     * @param localPath
     * @param fileName
     * @return java.lang.Boolean
     **/
    public Boolean upload2OssByFile(String localPath, String fileName) {
        try {
            ossClient.putObject(bucket, fileName, new File(localPath));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * @Description byte数组上传
     * @Author Xiaoma
     * @Date 2021/8/27 16:54
     * @param bytes
     * @param fileName
     * @return java.lang.Boolean
     **/
    public Boolean upload2OssByBytes(byte[] bytes, String fileName) {
        try {
            ossClient.putObject(bucket, fileName, new ByteArrayInputStream(bytes));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
    }
    /**
     * @Description  下载文件到本地
     * @Author Xiaoma
     * @Date 2021/8/27 16:31
     * @param objectName
     * @param localPath
     * @return java.lang.Boolean
     **/
    public Boolean download2Local(String objectName, String localPath) {
        try {
            ossClient.getObject(new GetObjectRequest(bucket, objectName), new File(localPath));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }

    }

    /**
     * @param
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Description 返回签名
     * @Author Xiaoma
     * @Date 2021/8/27 16:26
     **/
    public Map<String, String> policy() {

        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format; // 用户上传文件时指定的前缀。

        Map<String, String> respMap = null;
        try {
            // 签名有效事件
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return respMap;
    }
    /**
     * @Description  根据bucketName和文件名获取Oss文件下载地址
     * @Author Xiaoma
     * @Date 2021/8/27 16:54
     * @param filePath
     * @param fileName
     * @param httpRequest
     * @return java.lang.String
     **/
    public String getOssDownloadUrl(String filePath, String fileName, HttpServletRequest httpRequest) {
        try {
            // 服务器端生成url签名字串
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
                    bucket, filePath, HttpMethod.GET);
            ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
            Browser browser = UserAgent.parseUserAgentString(
                    httpRequest.getHeader("User-Agent")).getBrowser();
            String info = browser.getName().toLowerCase();
            // IE浏览器和火狐
            if ((info.contains("internet") && info.contains("explorer"))
                    || info.contains("firefox")) {
                String utfileName = URLEncoder.encode(fileName, "utf-8")
                        .replace("+", "%20");
                responseHeaders.setContentDisposition("attachment;filename*=UTF-8''" + utfileName);
            } else if (info.contains("microsoft ")) {// microsoft edge浏览器
                String utfileName = URLEncoder.encode(fileName, "utf-8")
                        .replace("+", "%20");
                responseHeaders.setContentDisposition("attachment;filename="
                        + utfileName);
            } else {
                responseHeaders.setContentDisposition("attachment;filename="
                        + new String(fileName.replaceAll(",", "").getBytes(
                        "UTF-8"), "UTF-8"));
            }
            responseHeaders.setContentType("application/octet-stream ");
            responseHeaders.setContentEncoding("UTF-8");
            responseHeaders.setExpires(expiration.toString());
            request.setResponseHeaders(responseHeaders);
            // 设置过期时间
            request.setExpiration(expiration);
            // 生成URL签名(HTTP GET请求)
            URL signedUrl = ossClient.generatePresignedUrl(request);
            return signedUrl.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
